package com.cloudservice.ccs.biz.impl;

import com.cloudservice.ccs.biz.ISystemMessageBiz;
import com.cloudservice.ccs.entity.SystemMessage;
import com.cloudservice.ccs.exception.SystemMessageException;
import com.cloudservice.ccs.mapper.SystemMessageMapper;
import com.cloudservice.ccs.model.ApiResult;
import com.cloudservice.ccs.websocket.NoticeAndSystemMessageServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Service
public class SystemMessageImpl implements ISystemMessageBiz {

	private final Logger logger = LoggerFactory.getLogger(SystemMessageImpl.class);

	@Autowired
	SystemMessageMapper systemMessageMapper;

	@Override
	public void save(SystemMessage systemMessage) {
		int result = systemMessageMapper.save(systemMessage);
		if (result == 0) {
			throw new SystemMessageException("Create SystemMessage entity error");
		}
		try {
			NoticeAndSystemMessageServer.getSessionPool().broadcast(ApiResult.successWithData(systemMessage));
		} catch (IOException e) {
			if (logger.isWarnEnabled()) {
				logger.warn("Error when broadcasting new system message: " + e.getClass().getName() + ": " + e.getMessage());
				e.printStackTrace();
			}
		}
	}

	@Override
	public void update(Integer id, SystemMessage systemMessage) {
		int result = systemMessageMapper.update(id, systemMessage);
		if (result == 0) {
			throw new SystemMessageException("Update SystemMessage entity error");
		}
	}

	@Override
	public void partialUpdate(Integer id, Map<String, Object> fields) {
		int result = systemMessageMapper.partialUpdate(id, fields);
		if (result == 0) {
			throw new SystemMessageException("Partial update SystemMessage failed");
		}
	}

	@Override
	public void delete(Integer id) {
		int result = systemMessageMapper.delete(id);
		if (result == 0) {
			throw new SystemMessageException("Delete SystemMessage entity error");
		}
	}

	@Override
	public SystemMessage getOne(Integer id) {
		SystemMessage systemMessage = systemMessageMapper.getOne(id);
		if (systemMessage == null) {
			throw new SystemMessageException("Get SystemMessage entity error: no such entity");
		}
		return systemMessage;
	}

	@Override
	public List<SystemMessage> getAll() {
		return systemMessageMapper.getAll();
	}
}
